package com.pyue.eam.regi.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyue.eam.admin.api.entity.regi.CqTaskMsgEntity;
import com.pyue.eam.app.service.AppUserService;
import com.pyue.eam.common.security.service.EamUser;
import com.pyue.eam.common.security.util.SecurityUtils;
import com.pyue.eam.regi.mapper.CqTaskMsgMapper;
import com.pyue.eam.regi.service.CqTaskMsgService;
import com.pyue.eam.admin.utils.WxPushMessageUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 任务消息
 *
 * @date 2023-11-17 15:34:32
 */
@Service
@AllArgsConstructor
public class CqTaskMsgServiceImpl extends ServiceImpl<CqTaskMsgMapper, CqTaskMsgEntity> implements CqTaskMsgService {
    private final AppUserService appUserService;

    @Override
    public Long saveData(CqTaskMsgEntity cqTaskMsg) {
        final EamUser user = SecurityUtils.getUser();
        cqTaskMsg.setUserAvatar(user.getAvatar());
        cqTaskMsg.setRealName(StrUtil.isNotBlank(user.getName()) ? user.getName() : user.getNickname());

        save(cqTaskMsg);

        // 找到这个消息的所有参与用户id
        List<Long> userIdList = baseMapper.getTaskMesUserIdList(cqTaskMsg.getTaskId());

        if (CollUtil.isNotEmpty(userIdList)) {
            List<String> wxOpenIdListByAppUserId = appUserService.getWxOpenIdByAppUserId(userIdList);
            WxPushMessageUtil.sendMessage(wxOpenIdListByAppUserId, "您有新的小程序任务消息，请注意查收！");
        }
        return cqTaskMsg.getId();
    }
}
